﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using easytodoservice.Model;

namespace easytodoservice.Infrastructure
{
    [Export(typeof(INoteRepository))]
    public class NoteRepository : INoteRepository
    {
        readonly TodoEntities _entities = new TodoEntities();

        public void Update(Note updatedNote)
        {
            var note = _entities.Note.SingleOrDefault(n => n.ID == updatedNote.ID);
            
            if(note == null)
                return;

            note.Modified = updatedNote.Modified = DateTime.Now;
            note.Priority = updatedNote.Priority;
            note.Title = updatedNote.Title;
            note.Text = updatedNote.Text;
            note.DueDate = updatedNote.DueDate;

            _entities.SaveChanges();
        }

        public Note Get(int id)
        {
            return _entities.Note.SingleOrDefault(n => n.ID == id);
        }

        public IQueryable<Note> GetAll()
        {
            return _entities.Note.AsQueryable();
        }

        public void Post(Note note)
        {
            if (note == null)
                return;

            note.Created = DateTime.Now;

            _entities.Note.AddObject(note);
            _entities.SaveChanges();
        }

        public void Delete(int id)
        {
            var note = _entities.Note.SingleOrDefault(n => n.ID == id);
            
            if(note == null)
                return;

            _entities.Note.DeleteObject(note);
            _entities.SaveChanges();
        }
    }
}